<template>
  <div class="dashboard">
    <h1 class="page-title">今日概览</h1>

    <!-- 今日进度 -->
    <el-card class="content-card progress-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>今日任务进度</span>
          <el-tag :type="progressTagType">{{ progressText }}</el-tag>
        </div>
      </template>
      
      <div class="progress-content">
        <el-progress
          :percentage="completionRate"
          :color="progressColor"
          :stroke-width="20"
          :text-inside="true"
        />
        <div class="progress-stats">
          <div class="stat-item">
            <span class="stat-label">已完成</span>
            <span class="stat-value success">{{ dailyProgress.completed }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">总任务</span>
            <span class="stat-value">{{ dailyProgress.total }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 今日任务列表 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>今日任务列表</span>
          <el-button type="primary" size="small" @click="goToCheckIn">
            去打卡
          </el-button>
        </div>
      </template>

      <div v-loading="loading" class="tasks-list">
        <el-empty v-if="todayTasks.length === 0" description="今天还没有安排任务">
          <el-button type="primary" @click="goToTaskAssign">去分配任务</el-button>
        </el-empty>

        <div
          v-for="item in todayTasks"
          :key="item.id"
          class="task-item"
          :class="{ 'completed': item.status === 1 }"
        >
          <div class="task-info">
            <el-icon class="task-icon">
              <CircleCheck v-if="item.status === 1" />
              <Clock v-else />
            </el-icon>
            <div class="task-content">
              <h3>{{ item.task?.title }}</h3>
              <p>{{ item.task?.description }}</p>
              <div class="task-meta">
                <el-tag size="small" type="info">
                  {{ getDomainText(item.task?.domain) }}
                </el-tag>
                <el-tag size="small" type="warning">
                  {{ getDifficultyText(item.task?.difficulty) }}
                </el-tag>
                <span class="task-time">
                  <el-icon><Clock /></el-icon>
                  {{ item.scheduledTime }}
                </span>
              </div>
            </div>
          </div>
          <div class="task-actions">
            <el-tag v-if="item.status === 1" type="success" size="large">
              已完成
            </el-tag>
            <template v-else>
              <el-button
                type="primary"
                size="large"
                @click="quickCheckIn(item)"
              >
                立即打卡
              </el-button>
              <el-button
                type="danger"
                size="large"
                plain
                @click="removePlanItem(item)"
                style="margin-left: 10px"
              >
                移除
              </el-button>
            </template>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 能力发展概览 -->
    <el-card class="content-card ability-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>能力发展概览</span>
            <el-tag size="small" type="info" style="margin-left: 10px">近1周平均得分</el-tag>
          </div>
          <el-button type="text" size="small" @click="goToProgressCenter">
            查看详情 →
          </el-button>
        </div>
      </template>

      <div v-loading="loadingAbility" class="ability-overview">
        <div
          v-for="domain in abilityStats"
          :key="domain.domain"
          class="ability-item"
        >
          <div class="ability-header">
            <div class="ability-icon" :style="{ background: getDomainColor(domain.domain) }">
              {{ getDomainIcon(domain.domain) }}
            </div>
            <div class="ability-info">
              <div class="ability-name">{{ domain.domainName }}</div>
              <div class="ability-meta">
                <span class="meta-label">周平均</span>
                <span class="meta-value">{{ domain.averageScore.toFixed(1) }}分</span>
                <template v-if="Math.abs(domain.trend) >= 0.1">
                  <el-icon v-if="domain.trend > 0" color="#67c23a" class="trend-icon"><CaretTop /></el-icon>
                  <el-icon v-else color="#f56c6c" class="trend-icon"><CaretBottom /></el-icon>
                  <span :class="domain.trend > 0 ? 'trend-up' : 'trend-down'" class="trend-text">
                    {{ domain.trend > 0 ? '+' : '' }}{{ domain.trend.toFixed(1) }}
                  </span>
                </template>
              </div>
            </div>
          </div>
          <el-progress
            :percentage="domain.averageScore || 0"
            :color="getDomainColor(domain.domain)"
            :stroke-width="12"
            :show-text="true"
          >
            <template #default="{ percentage }">
              <span class="progress-text">{{ percentage.toFixed(0) }}分</span>
            </template>
          </el-progress>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getDailyTasks, deletePlanItem } from '@/api/plan'
import { getDailyProgress, getMultiDomainCurve } from '@/api/progress'
import { DOMAIN_MAP, DIFFICULTY_MAP, DOMAIN_OPTIONS } from '@/utils/constants'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loading = ref(false)
const loadingAbility = ref(false)
const todayTasks = ref([])
const dailyProgress = ref({
  completed: 0,
  total: 0,
  rate: 0
})
const abilityStats = ref([])

const domainList = DOMAIN_OPTIONS

// 计算完成率
const completionRate = computed(() => {
  return dailyProgress.value.total === 0
    ? 0
    : Math.round((dailyProgress.value.completed / dailyProgress.value.total) * 100)
})

const progressText = computed(() => {
  const rate = completionRate.value
  if (rate === 100) return '全部完成'
  if (rate >= 80) return '即将完成'
  if (rate >= 50) return '进行中'
  return '刚开始'
})

const progressTagType = computed(() => {
  const rate = completionRate.value
  if (rate === 100) return 'success'
  if (rate >= 50) return 'warning'
  return 'info'
})

const progressColor = '#f9a8d4'

const getDomainText = (domain) => {
  return DOMAIN_MAP[domain] || domain
}

const getDifficultyText = (difficulty) => {
  return DIFFICULTY_MAP[difficulty] || difficulty
}

// 领域颜色配置
const domainColors = {
  social: '#fbcfe8',         // 社交能力 - 淡粉色
  emotion: '#fed7aa',        // 情绪管理 - 淡橙色
  selfcare: '#a7f3d0',       // 生活自理 - 淡青色
  communication: '#fecaca',  // 沟通交流 - 淡红色
  cognition: '#ddd6fe',      // 认知能力 - 淡紫色
  motor: '#a5f3fc'           // 行为干预 - 淡蓝色
}

// 领域图标配置
const domainIcons = {
  social: '👥',
  emotion: '😊',
  selfcare: '🧒',
  communication: '💬',
  cognition: '🧠',
  motor: '🏃'
}

const getDomainColor = (domain) => {
  return domainColors[domain] || '#409eff'
}

const getDomainIcon = (domain) => {
  return domainIcons[domain] || '📊'
}

// 加载能力发展数据
const loadAbilityStats = async () => {
  loadingAbility.value = true
  try {
    const userId = userStore.userInfo?.userId
    if (!userId) return

    // 计算近1周的日期范围
    const endDate = dayjs()
    const startDate = endDate.subtract(1, 'week')
    
    const data = await getMultiDomainCurve({ 
      userId, 
      startDate: startDate.format('YYYY-MM-DD'),
      endDate: endDate.format('YYYY-MM-DD')
    })
    
    // 计算每个领域的平均得分和趋势
    const stats = []
    const domainNames = {
      social: '社交能力',
      emotion: '情绪管理',
      selfcare: '生活自理',
      communication: '沟通交流',
      cognition: '认知能力',
      motor: '行为干预'
    }

    for (const [domain, scores] of Object.entries(data.domainData || {})) {
      if (scores && scores.length > 0) {
        // 计算平均分
        const averageScore = scores.reduce((sum, score) => sum + score, 0) / scores.length
        
        // 计算趋势（最后一天与第一天的差值）
        const trend = scores.length > 1 ? scores[scores.length - 1] - scores[0] : 0
        
        stats.push({
          domain,
          domainName: domainNames[domain] || domain,
          averageScore: Math.round(averageScore * 10) / 10,
          trend: Math.round(trend * 10) / 10
        })
      }
    }

    abilityStats.value = stats
  } catch (error) {
    console.error('加载能力数据失败:', error)
  } finally {
    loadingAbility.value = false
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const userId = userStore.userInfo?.userId
    if (!userId) return

    // 获取今日任务
    const tasks = await getDailyTasks({ userId })
    todayTasks.value = tasks || []

    // 获取今日进度
    const progress = await getDailyProgress({ userId })
    dailyProgress.value = progress || { completed: 0, total: 0, rate: 0 }
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
  
  // 同时加载能力统计
  loadAbilityStats()
}

// 快速打卡
const quickCheckIn = (item) => {
  router.push({
    path: '/app/check-in',
    query: { taskId: item.taskId, planItemId: item.id }
  })
}

// 移除计划项
const removePlanItem = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除任务"${item.task?.title}"吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const userId = userStore.userInfo?.userId
    await deletePlanItem(item.id, userId)
    ElMessage.success('已移除任务')
    
    // 重新加载数据
    await loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除任务失败:', error)
      ElMessage.error('移除任务失败')
    }
  }
}

// 导航
const goToCheckIn = () => {
  router.push('/app/check-in')
}

const goToTaskAssign = () => {
  router.push('/app/task-assign')
}

const goToProgressCenter = () => {
  router.push('/app/progress-center')
}

onMounted(() => {
  loadData()
})

// 监听路由变化，当回到首页时重新加载数据
watch(() => route.path, (newPath) => {
  if (newPath === '/app/dashboard') {
    loadData()
  }
})
</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.progress-card {
  background: linear-gradient(135deg, #fef5f8 0%, #fef9f5 100%);
  border: 1px solid #fce7f3;
  box-shadow: 0 8px 24px rgba(251, 207, 232, 0.15);
}

.progress-content {
  padding: 20px 0;
}

.progress-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 30px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  display: block;
  font-size: 32px;
  font-weight: bold;
  color: #303133;
}

.stat-value.success {
  color: #f472b6;
}

.tasks-list {
  min-height: 200px;
}

.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  margin-bottom: 15px;
  background: #fefbfc;
  border-radius: 12px;
  border-left: 4px solid #fbcfe8;
  box-shadow: 0 2px 8px rgba(251, 207, 232, 0.08);
  transition: all 0.3s;
}

.task-item:hover {
  background: #fff;
  box-shadow: 0 4px 16px rgba(251, 207, 232, 0.15);
  transform: translateY(-2px);
  border-left-color: #f9a8d4;
}

.task-item.completed {
  opacity: 0.7;
  border-left-color: #67c23a;
}

.task-info {
  display: flex;
  align-items: flex-start;
  flex: 1;
  gap: 15px;
}

.task-icon {
  font-size: 32px;
  color: #f9a8d4;
  margin-top: 5px;
}

.task-item.completed .task-icon {
  color: #67c23a;
}

.task-content {
  flex: 1;
}

.task-content h3 {
  font-size: 16px;
  color: #303133;
  margin: 0 0 5px 0;
}

.task-content p {
  font-size: 14px;
  color: #606266;
  margin: 0 0 10px 0;
}

.task-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.task-time {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #909399;
}

.task-actions {
  margin-left: 20px;
}

.ability-card {
  background: linear-gradient(135deg, #fefbfc 0%, #fef5f8 100%);
  border: 1px solid #fce7f3;
  box-shadow: 0 4px 16px rgba(251, 207, 232, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
}

.ability-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  padding: 10px 0;
}

.ability-item {
  padding: 20px;
  background: #fffbfc;
  border-radius: 16px;
  border: 1px solid #fce7f3;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(251, 207, 232, 0.05);
}

.ability-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(251, 207, 232, 0.15);
  border-color: #fbcfe8;
  background: #fff;
}

.ability-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.ability-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.ability-info {
  flex: 1;
}

.ability-name {
  font-size: 16px;
  color: #303133;
  margin-bottom: 4px;
  font-weight: 600;
}

.ability-meta {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
}

.meta-label {
  color: #909399;
  font-size: 12px;
}

.meta-value {
  color: #303133;
  font-weight: 600;
  font-size: 14px;
}

.trend-icon {
  font-size: 14px;
  margin-left: 4px;
}

.trend-text {
  font-weight: 600;
  font-size: 12px;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

.progress-text {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}

@media (max-width: 768px) {
  .ability-overview {
    grid-template-columns: 1fr;
  }
  
  .task-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .task-actions {
    margin-left: 0;
    margin-top: 15px;
    width: 100%;
  }
  
  .task-actions .el-button {
    width: 100%;
  }

  .ability-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }

  .ability-name {
    font-size: 15px;
  }
}
</style>
